<template>
	<view class="page-container">
		<!-- 导航栏 -->
		<nav-bar title="登录" :customBack="goHome"></nav-bar>
		
		<!-- 页面内容 -->
		<view class="page-content has-nav-bar">
			<view class="logo-area">
				<image src="/static/logo.png" mode="aspectFit" class="logo"></image>
				<text class="app-name">宠物星球</text>
				<text class="app-slogan">您身边的宠物专家</text>
			</view>

		<view class="form-area">
			<view class="tab-switcher">
				<view class="tab-item" :class="{ 'active': currentTab === 0 }" @click="changeTab(0)">
					账号登录
				</view>
				<view class="tab-item" :class="{ 'active': currentTab === 1 }" @click="changeTab(1)">
					验证码登录
				</view>
			</view>

			<!-- 账号密码登录 -->
			<view v-show="currentTab === 0" class="form-content">
				<u-form :model="accountForm" ref="accountForm" :rules="rules.accountForm">
					<u-form-item prop="username">
						<u-input v-model="accountForm.username" placeholder="请输入用户名/手机号/邮箱" prefixIcon="account-fill"
							clearable>
						</u-input>
					</u-form-item>
					<u-form-item prop="password">
						<u-input v-model="accountForm.password" type="password" placeholder="请输入密码"
							prefixIcon="lock-fill" clearable>
						</u-input>
					</u-form-item>
				</u-form>
			</view>
			<!-- 验证码登录 -->
			<view v-show="currentTab === 1" class="form-content">
				<u-form :model="smsForm" ref="smsForm" :rules="rules.smsForm">
					<u-form-item prop="phone">
						<u-input v-model="smsForm.phone" placeholder="请输入手机号" prefixIcon="phone-fill" clearable>
						</u-input>
					</u-form-item>
					<u-form-item prop="code">
						<u-input v-model="smsForm.code" placeholder="请输入验证码" prefixIcon="email-fill" clearable>
							<template #suffix>
								<u-code ref="refCode" @change="codeChange" seconds="60" changeText="X秒重新获取"></u-code>
								<u-button @tap="getCode" :text="codeTips" type="success" size="mini"
									:disabled="isSending"></u-button>
							</template>
						</u-input>
					</u-form-item>
				</u-form>
			</view>

			<view class="login-button">
				<u-button type="primary" shape="circle" @click="handleLogin">登 录</u-button>
			</view>

			<view class="extra-links">
				<text>忘记密码</text>
				<text @click="goRegister">立即注册</text>
			</view>
		</view>
		</view>
	</view>
</template>

<script>
import uForm from '@/node_modules/uview-ui/components/u-form/u-form.vue'
import uFormItem from '@/node_modules/uview-ui/components/u-form-item/u-form-item.vue'
import uInput from '@/node_modules/uview-ui/components/u-input/u-input.vue'
import uButton from '@/node_modules/uview-ui/components/u-button/u-button.vue'
import uCode from '@/node_modules/uview-ui/components/u-code/u-code.vue'
import NavBar from '@/components/NavBar.vue'
import {
	userApi
} from '../../src/api/user.js'

export default {
	components: {
		uForm,
		uFormItem,
		uInput,
		uButton,
		uCode,
		NavBar
	},
	data() {
		return {
			currentTab: 0, // 0: 账号登录, 1: 验证码登录
			accountForm: {
				username: '',
				password: ''
			},
			smsForm: {
				phone: '',
				code: ''
			},
			rules: {
				accountForm: {
					username: [{
						required: true,
						message: '请输入用户名/手机号/邮箱',
						trigger: ['blur', 'change']
					}],
					password: [{
						required: true,
						message: '请输入密码',
						trigger: ['blur', 'change']
					}]
				},
				smsForm: {
					phone: [{
						required: true,
						message: '请输入手机号',
						trigger: ['blur', 'change']
					},
					{
						validator: (rule, value, callback) => {
							return uni.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						trigger: ['change', 'blur'],
					}
					],
					code: [{
						required: true,
						message: '请输入验证码',
						trigger: ['blur', 'change']
					}]
				}
			},
			codeTips: '获取验证码',
			isSending: false,
			refCode: null
		};
	},
	methods: {
		// 返回首页
		goHome() {
			uni.reLaunch({
				url: '/pages/shop/index'
			});
		},
		changeTab(index) {
			this.currentTab = index;
		},
		handleLogin() {
			if (this.currentTab === 0) {
				this.accountLogin();
			} else {
				this.smsLogin();
			}
		},
		accountLogin() {
			this.$refs.accountForm.validate().then(res => {
				console.log('表单验证成功', this.accountForm);

				userApi.login(this.accountForm).then(res => {
					if (res && res.code === 200 && res.data) {
						uni.setStorageSync('token', res.data.token);
						uni.setStorageSync('userInfo', res.data.user);
						uni.showToast({
							title: '登录成功',
							icon: 'success'
						});
						// 登录成功后跳转到我的页面
						uni.redirectTo({
							url: '/pages/my/index'
						});
					} else {
						uni.showToast({
							title: res.message || '登录失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					console.error('API请求错误:', err);
					uni.showToast({
						title: err.message || '网络错误，请稍后再试',
						icon: 'none'
					});
				});

			}).catch(errors => {
				console.log('表单验证失败', errors);
			});
		},
		smsLogin() {
			this.$refs.smsForm.validate().then(res => {
				console.log('表单验证成功');
				userApi.smsLogin(this.smsForm).then(res => {
					if (res && res.code === 200 && res.data) {
						uni.setStorageSync('token', res.data.token);
						uni.setStorageSync('userInfo', res.data.user);
						uni.showToast({
							title: '登录成功',
							icon: 'success'
						});
						// 登录成功后跳转到我的页面
						uni.redirectTo({
							url: '/pages/my/index'
						});
					} else {
						uni.showToast({
							title: res.message || '登录失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					console.error('API请求错误:', err);
					uni.showToast({
						title: err.message || '网络错误，请稍后再试',
						icon: 'none'
					});
				});
			}).catch(errors => {
				console.log('表单验证失败', errors);
			});
		},
		getCode() {
			if (this.isSending) return;
			this.$refs.smsForm.validateField('phone', (valid) => {
				if (valid && valid.length) {
					// 验证失败
					return;
				}

				this.isSending = true;
				userApi.sendSmsCode(this.smsForm.phone, 'login').then(res => {
					uni.showToast({
						title: '验证码已发送',
						icon: 'success'
					});
					if (this.$refs.refCode) {
						this.$refs.refCode.start();
					}
				}).catch(err => {
					this.isSending = false;
					uni.showToast({
						title: '验证码发送失败',
						icon: 'none'
					});
				})
			});
		},
		codeChange(text) {
			this.codeTips = text;
		},
		goRegister() {
			uni.navigateTo({
				url: '/pages/register/index'
			});
		}
	},
	onReady() {
		if (this.$refs.accountForm) {
			this.$refs.accountForm.setRules(this.rules.accountForm);
		}
		if (this.$refs.smsForm) {
			this.$refs.smsForm.setRules(this.rules.smsForm);
		}
	}
}
</script>

<style lang="scss">
.page-container {
	display: flex;
	flex-direction: column;
	padding: 100rpx 40rpx;
	background-color: $page-bg-color;
	min-height: 100vh;
	box-sizing: border-box;
}

.logo-area {
	text-align: center;
	align-items: center;
	margin-bottom: 80rpx;

	.logo {
		width: 160rpx;
		height: 160rpx;
		border-radius: 50%;
		box-shadow: $shadow;
	}

	.app-name {
		display: block;
		font-size: 44rpx;
		font-weight: bold;
		color: $text-primary-color;
		margin-top: 30rpx;
	}

	.app-slogan {
		display: block;
		font-size: 28rpx;
		color: $text-secondary-color;
		margin-top: 15rpx;
	}
}

.form-area {
	background-color: $card-bg-color;
	padding: 60rpx 50rpx;
	border-radius: 24rpx;
	box-shadow: $shadow;
}

.tab-switcher {
	display: flex;
	margin-bottom: 60rpx;

	.tab-item {
		flex: 1;
		text-align: center;
		padding-bottom: 20rpx;
		font-size: 34rpx;
		color: $text-secondary-color;
		position: relative;
		transition: color 0.3s;

		&.active {
			color: $theme-color;
			font-weight: bold;

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 80rpx;
				height: 8rpx;
				background-color: $theme-color;
				border-radius: 4rpx;
			}
		}
	}
}

.form-content {
	/deep/ .u-form-item {
		padding: 10rpx 0;
	}

	/deep/ .u-input {
		background-color: $page-bg-color;
		padding: 12rpx 24rpx !important;
		border-radius: 16rpx;
	}
}

.extra-links {
	display: flex;
	justify-content: space-between;
	font-size: 26rpx;
	color: $text-secondary-color;
	margin-top: 40rpx;
}

.login-button {
	margin-top: 80rpx;

	/deep/ .u-button--primary {
		background-color: $theme-color;
		border-color: $theme-color;
		box-shadow: 0 8rpx 16rpx rgba(217, 109, 0, 0.2);
	}
}
</style>